package com.example.blogsystem.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtils {
    private static final long EXPIATION = 60 * 60 * 1000;
    private static final String KEY_STRING = "F1ZSY7rFvFoz3q/XjrCNW7ygjv0vzwJEpkydzaI8ZJ8=";
    private static final Key KEY = Keys.hmacShaKeyFor(Decoders.BASE64.decode(KEY_STRING));

    public static String genToken(Map<String, Object> claims){

        String token = Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIATION))
                .signWith(KEY)
                .compact();

        return token;
    }

    public static Claims parseToken(String token){
        if(token == null){
            return null;
        }
        //生成解析器
        JwtParser build = Jwts.parserBuilder().setSigningKey(KEY).build();
        Claims claims = null;
        try{
            claims = build.parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException expiredJwtException){
            log.info("token已过期, 有效截止日期：{}", DateUtils.formatDate(expiredJwtException.getClaims().getExpiration()));
        } catch (Exception e){
            log.error("解析token失败, token:{}", token);
        }
        return claims;
    }

    public static String getUserEmailFromToken(String token){
        Claims claims = JwtUtils.parseToken(token);
        String email = null;
        if(claims != null){
            email = (String) claims.get("email");
        }
        return email;
    }
}
